package com.haruhinav.controller;


import com.haruhinav.Utils.Constants;
import com.haruhinav.Utils.FileUtil;
import com.haruhinav.entity.Wallpaper;
import com.haruhinav.entity.vo.ImageDetails;
import com.haruhinav.entity.vo.ResultVO;
import com.haruhinav.service.WallpaperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;

@RestController
@RequestMapping("/api/wall")
public class WallpaperController {

    @Autowired
    private WallpaperService wallpaperService;
    @Autowired
    private FileUtil fileUtil;

    /**
     * 分页获取壁纸
     * @param currentPage
     * @param pageSize
     * @return
     */
    @PostMapping("/e/list/{pageSize}/{currentPage}")
    public ResultVO getWallpaper(@PathVariable Integer pageSize,@PathVariable Integer currentPage,@RequestBody Wallpaper wallpaper){
        ResultVO result = new ResultVO();
        if(ObjectUtils.isEmpty(currentPage)){
            result.setCode(-1);
            result.setType("error");
            result.setMsg("参数错误");
            return result;
        }
        if(ObjectUtils.isEmpty(pageSize)){
            pageSize = 24;
        }
        // 前端用户使用,只需要两个参数
        wallpaper.setPage((currentPage-1)*pageSize);
        wallpaper.setPageSize(pageSize);

        result.setData(wallpaperService.limitWallpaper(wallpaper));
        return result;
    }

    /**
     * 单图片/壁纸上传 提供给用户
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/a/upload")
    public ResultVO upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        ResultVO result  = new ResultVO();

        if (null==file||file.isEmpty()) {
            result.setCode(-1);
            result.setMsg("无文件");
            result.setType("warning");
            return result;
        }
        ImageDetails details = fileUtil.getImageDetails(file);
//        System.out.println(details);
        if(null==details){
            result.setCode(-2);
            result.setMsg("失败！请上传图片文件！");
            result.setType("warning");
            return result;
        }
        // 判断大小
        if(details.getSize() > 8f ){
            result.setCode(-2);
            result.setMsg("失败！文件不得大于8MB！");
            result.setType("warning");
            return result;
        }
        if(details.getSize() < 0.5f ){
            result.setCode(-2);
            result.setMsg("失败！画质不够哦!");
            result.setType("warning");
            return result;
        }
        // 还未审核的壁纸uuid名不能返回给普通用户
        // result.setData(null);
        return wallpaperService.upload(file, details, request, false);
    }
}
